package com.freesun.shop.controller;

import com.freesun.shop.anno.Log;
import com.freesun.shop.entity.SysMenu;
import com.freesun.shop.entity.SysUser;
import com.freesun.shop.service.SysMenuService;
import com.freesun.shop.vo.MenuAuths;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sys/menu")
public class MenuController {

    private static Logger log = LoggerFactory.getLogger(MenuController.class);
    @Autowired
    private SysMenuService sysMenuService;

    @ApiModelProperty("加载用户的权限的菜单")
    @GetMapping("nav")
    public ResponseEntity<MenuAuths> loadMenuAuths(){
        //获取用户对象
      SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
      if(null==user){
          return null;
      }
      log.info("开始加载id为:{},用户的权限和id数据",user.getUserId());
        MenuAuths menuAuths = sysMenuService.loadMenuAndAuths(user.getUserId());
        return ResponseEntity.ok(menuAuths);
    }

    @ApiOperation("查询菜单的列表")
    @GetMapping("/table")
    @Log(name = "查询菜单的列表")
    public ResponseEntity<List<SysMenu>> listMenu(){
        List<SysMenu> sysMenus = sysMenuService.list();
        return ResponseEntity.ok(sysMenus);
    }
    @ApiOperation("菜单的列表查询,只查询菜单,不查询按钮")
    @GetMapping("/list")
    @Log(name = "菜单的列表查询,只查询菜单,不查询按钮")
    public ResponseEntity<List<SysMenu>> listMenuNoPermission(){
        List<SysMenu> sysMenus = sysMenuService.listMenuNoButtn();
        return ResponseEntity.ok(sysMenus);
    }

    @ApiOperation("删除菜单")
    @DeleteMapping("/{id}")
    @Log(name = "删除菜单")
    public ResponseEntity<Void> deleteMenu(@PathVariable("id") Long id){
        sysMenuService.removeById(id);
        return ResponseEntity.ok().build();
    }
    @ApiOperation("新增一个菜单")
    @PostMapping
    @Log(name = "新增菜单")
    public ResponseEntity<Void> addMenu(@RequestBody SysMenu sysMenu){
        sysMenuService.save(sysMenu);
        return ResponseEntity.ok().build();
    }
    @ApiOperation("查询一个菜单")
    @GetMapping("/info/{id}")
    @Log(name = "查询菜单")
    public ResponseEntity<SysMenu> getMenuById(@PathVariable("id") Long id){
        SysMenu sysMenu = sysMenuService.getById(id);
        return ResponseEntity.ok(sysMenu);
    }

    @ApiOperation("修改菜单")
    @PutMapping
    @Log(name = "修改菜单")
    public ResponseEntity<Void> updateMenuById(@RequestBody SysMenu sysMenu){
       sysMenuService.updateById(sysMenu);
        return ResponseEntity.ok().build();
    }
}
